package cn.wolfcode.shop.service.impl;

import cn.wolfcode.shop.domain.User;
import cn.wolfcode.shop.mapper.UserMapper;
import cn.wolfcode.shop.redis.RedisService;
import cn.wolfcode.shop.redis.key.UserKeyPrefix;
import cn.wolfcode.shop.service.IUserService;
import cn.wolfcode.shop.util.MD5Util;
import cn.wolfcode.shop.exception.GlobalException;
import cn.wolfcode.shop.result.CodeMsg;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.UUID;

/**
 * Created by wolfcode-lanxw
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisService redisService;
    @Override
    public User getById(Long id) {
        User user = redisService.get(UserKeyPrefix.USER_BY_ID,""+id,User.class);
        if(user!=null){
            if(user.getId()!=null){
                return user;
            }else{
                return null;
            }
        }
        if(redisService.exists(UserKeyPrefix.USER_BY_ID,""+id)){
            return null;
        }
        String uuid = UUID.randomUUID().toString();
        boolean lock = redisService.tryGetDistributedLock(UserKeyPrefix.USER_BY_ID_LOCK+":"+id, uuid, 10);
        if(!lock){
            return null;
        }
        user = userMapper.getById(id);
        if(user!=null){
            redisService.set(UserKeyPrefix.USER_BY_ID,""+id,user);
        }else{
            redisService.set(UserKeyPrefix.USER_BY_ID_NULL,""+id,new User());
        }
        boolean result = redisService.releaseDistributedLock(UserKeyPrefix.USER_BY_ID_LOCK + ":" + id, uuid);
        return user;
    }
    @Override
    public String login(String mobile, String password) throws GlobalException {
        User user = this.getById(Long.parseLong(mobile));
        if(user == null){
            throw new GlobalException(CodeMsg.LOGIN_ERROR);
        }
        String dbPassword = user.getPassword();
        String salt = user.getSalt();
        String calPass = MD5Util.formPassToDbPass(password,salt);
        if(!calPass.equals(dbPassword)){
            throw new GlobalException(CodeMsg.LOGIN_ERROR);
        }
        String token = createToken(user);
        return token;
    }

    private String createToken(User user) {
        String token = UUID.randomUUID().toString().replace("-","");
        redisService.set(UserKeyPrefix.USER_TOKEN,token,user);
        return token;
    }

}
